<template>
    <div v-loading="firstLoading" class="h-full">
        <el-scrollbar>
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-position="left"
                label-width="120px"
                class="py-4 px-10"
            >
                <el-form-item label="知识库图标" prop="logo">
                    <upload-single v-model="formData.logo" type="image" />
                </el-form-item>
                <el-form-item label="知识库名称" prop="name">
                    <div class="w-[380px]">
                        <el-input v-model="formData.name" placeholder="请输入知识库名称" />
                    </div>
                </el-form-item>
                <el-form-item label="知识库简介" prop="intro">
                    <div class="w-[380px]">
                        <el-input
                            v-model="formData.intro"
                            type="textarea"
                            placeholder="请输入知识库描述"
                            :rows="5"
                            resize="none"
                        />
                    </div>
                </el-form-item>

                <div class="w-[480px] mx-2">
                    <el-divider style="border-color: var(--el-border-color-extra-light)" />
                </div>

                <el-form-item label="训练索引模型" prop="vector_model">
                    <template #label>
                        <el-popover
                            placement="right"
                            :width="300"
                            trigger="hover"
                            content="向量模型可以将自然语言转成向量(即数据训练), 用于进行语义检索, 注意: 不同向量模型无法一起使用, 请不要随意修改。"
                        >
                            <template #reference>
                                <div class="flex items-center cursor-pointer text-[#666]">
                                    <span class="mr-1">训练索引模型</span>
                                    <icon name="el-icon-QuestionFilled" :size="14" />
                                </div>
                            </template>
                        </el-popover>
                    </template>
                    <div class="w-[380px]">
                        <models-select
                            v-model="formData.vector_model"
                            :disabled="false"
                            :updating="false"
                            type="vector"
                            @change="changeVector"
                        />
                    </div>
                </el-form-item>

                <el-form-item label="文件处理模型" prop="splits_model">
                    <template #label>
                        <el-popover
                            placement="right"
                            :width="300"
                            trigger="hover"
                            content="该模型用于导入数据时选择(问答拆分)模式时使用,利用大模型的能力对导入分段的内容生成一问一答的数据(即QA数据)"
                        >
                            <template #reference>
                                <div class="flex items-center cursor-pointer text-[#666]">
                                    <span class="mr-1">文件处理模型</span>
                                    <icon name="el-icon-QuestionFilled" :size="14" />
                                </div>
                            </template>
                        </el-popover>
                    </template>
                    <div class="w-[380px]">
                        <models-select v-model="formData.splits_model" type="type" />
                    </div>
                </el-form-item>

                <el-form-item class="mt-8">
                    <el-button
                        type="primary"
                        :loading="loading"
                        :disabled="know.power < permissionEnum.EDIT"
                        @click="handleSubmit"
                    >保存</el-button>

                    <el-button
                        :loading="loading"
                        :disabled="know.power < permissionEnum.ADMIN"
                        @click="handleDelete"
                    >删除</el-button>
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </div>
</template>

<script setup lang="ts">
import { permissionEnum } from '~/enums/app'
import feedback from '~/utils/feedback'
import knowManageApi from '~/api/agent/know/manage'

const props = withDefaults(
    defineProps<{
        know: KnowManageDetailResponse
    }>(),
    {}
)

const router = useRouter()

// 首次加载
const firstLoading = ref<boolean>(true)

// 表单信息
const loading = ref<boolean>(false)
const formRef = shallowRef()

// 表单数据
const formData: any = reactive({
    code: '',         // 编号
    logo: '',         // 图标
    name: '',         // 名称
    intro: '',        // 简介
    vector_model: '', // 向量模型
    splits_model: '', // 拆分模型
    is_disable: 0     // 是否禁用:[0=否, 1=是]
})

// 表单规则
const formRules: any = reactive({
    logo: [
        { required: true, message: '请上传知识库图标', trigger: 'blur' },
        { max: 250, message: '图标链接不能大于250个字符', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '知识库名称不能为空', trigger: 'blur' },
        { max: 32, message: '知识库名称不能大于32个字符', trigger: 'blur' }
    ],
    intro: [
        { required: true, message: '知识库简介不能为空', trigger: 'blur' },
        { max: 800, message: '知识库简介不能大于800个字符', trigger: 'blur' }
    ],
    vector_model: [
        { required: true, message: '请选择向量训练模型', trigger: 'blur' }
    ],
    splits_model: [
        { required: true, message: '请选择文件处理模型', trigger: 'blur' },
    ]
})

/**
 * 变更向量模型
 */
const changeVector = (data: any) => {
    if (formData.vector_model === data.name) {
        return
    }

    const msgTips = `
        <strong>您确定要切换向量模型吗?</strong> <br/> <br/>

        这是一个<strong style="color: #f27b66;">危险</strong>的操作，
        会对知识库所有内容从新训练。<br/>
        重新训练时间可能较长，另外请确保账号的余额充足。<br/> <br/>

        如果您智能体有绑定该知识库，请注意修改关联知识库，<br/>
        避免不同向量模型的知识库混用出现报错等问题。 <br/> <br/>

        请手动输入 <strong style="color: #FF5058;"'>确定切换</strong> 完成验证!
    `
    feedback.prompt(msgTips, '切换操作', {
        closeOnClickModal: false,
        closeOnPressEscape: false,
        dangerouslyUseHTMLString: true,
        inputPattern: /^确定切换$/,
        inputErrorMessage: '输入错误，请重新输入!'
    }).then(async () => {
        await knowManageApi.change_vector({
            code: formData.code,
            vector_model: data.name
        })
        formData.vector_model = data.name
        feedback.msgSuccess('变更成功')
    }).catch(() => {})
}

/**
 * 提交表单
 */
const handleSubmit = async (): Promise<void> => {
    await formRef.value?.validate().then(async () => {
        loading.value = true
        await knowManageApi.edit(formData)
            .finally(() => {
                setTimeout(() => {
                    loading.value = false
                }, 500)
            })

        feedback.msgSuccess('保存成功')
    }).catch(() => {})
}

/**
 * 提交删除
 */
const handleDelete = async (): Promise<void> => {
    const msgTips = `
        <strong>您要删除该知识库吗?</strong> <br/>
        <br/>
        一旦删除将无法恢复，并且会删除知识库的数据。<br/>
        <br/>
        请手动输入 <strong style="color: #FF5058;"'>删除知识库</strong> 完成验证!
    `

    feedback.prompt(msgTips, '删除知识库', {
        closeOnClickModal: false,
        closeOnPressEscape: false,
        dangerouslyUseHTMLString: true,
        inputPattern: /^删除知识库$/,
        inputErrorMessage: '输入错误，请重新输入!'
    }).then(async () => {
        loading.value = true
        await knowManageApi.delete(formData.code)
            .finally(() => {
                setTimeout(() => {
                    loading.value = false
                }, 500)
            })

        feedback.msgSuccess('删除成功')
        await router.push({
            path: '/agent/know'
        })
    }).catch(() => {})
}

watch(
    () => props.know,
    (val) => {
        for (const key in formData) {
            // @ts-ignore
            formData[key] = val[key]
        }
        firstLoading.value = false
    },
    { immediate: true }
)
</script>
